﻿using System.Collections.Generic;
using KaytechSoftware.Cms.Entities.Interfaces;

namespace KaytechSoftware.Cms.Entities
{
    public class UnitOfWorkService : IUnitOfWorkService
    {
        private readonly Dictionary<IUnitOfWork, List<IUnitOfWorkHolder>> _unitOfWorkHolders;
        private readonly Stack<IUnitOfWork> _unitOfWorkStack;

        public UnitOfWorkService()
        {
            _unitOfWorkHolders = new Dictionary<IUnitOfWork, List<IUnitOfWorkHolder>>();
            _unitOfWorkStack = new Stack<IUnitOfWork>();
        }

        #region IUnitOfWorkService Members

        public IUnitOfWork Create()
        {
            var unitOfWork = new UnitOfWork(this);
            _unitOfWorkStack.Push(unitOfWork);
            _unitOfWorkHolders[unitOfWork] = new List<IUnitOfWorkHolder>();
            return unitOfWork;
        }

        public IUnitOfWork GetCurrentUnitOfWork()
        {
            return _unitOfWorkStack.Peek();
        }

        public void Release(IUnitOfWork unitOfWork)
        {
            foreach (IUnitOfWorkHolder unitOfWorkHolder in _unitOfWorkHolders[unitOfWork])
            {
                unitOfWorkHolder.DetachFrom(unitOfWork);
            }
            _unitOfWorkHolders.Remove(unitOfWork);
            _unitOfWorkStack.Pop();
        }

        public void RegisterRepository(IUnitOfWork unitOfWork, IUnitOfWorkHolder repository)
        {
            _unitOfWorkHolders[unitOfWork].Add(repository);
        }

        public void UnregisterRepository(IUnitOfWork unitOfWork, IUnitOfWorkHolder repository)
        {
            _unitOfWorkHolders[unitOfWork].Remove(repository);
        }

        #endregion
    }
}
